// 确保DOM加载完成后执行
document.addEventListener("DOMContentLoaded", function () {
  // 获取所有带data-item-id属性的page__item元素
  const pageItems = document.querySelectorAll(".page__item[data-item-id]");

  // 使用定时器确保页面完全渲染后再执行
  setTimeout(function () {
    pageItems.forEach(function (pageItem) {
      try {
        // 获取当前page__item的data-item-id
        const itemId = pageItem.getAttribute("data-item-id");
        if (!itemId) return;

        // 查找对应的check__item
        const checkItem = document.querySelector(
          `.check__item[data-item-id="${itemId}"]`
        );

        if (checkItem) {
          // 计算page__item的实际高度，考虑padding和border
          console.log(pageItem);
          const pageItemHeight = pageItem.getBoundingClientRect().top;
          // 设置check__item的top位置
          checkItem.style.top = pageItemHeight + "px";

          // 添加鼠标悬停效果，增强交互性
          pageItem.addEventListener("mouseover", function () {
            checkItem.style.backgroundColor = "var(--primary-color)";
            checkItem.style.color = "var(--white)";
          });

          pageItem.addEventListener("mouseout", function () {
            checkItem.style.backgroundColor = "var(--white)";
            checkItem.style.color = "";
          });

          checkItem.addEventListener("mouseover", function () {
            pageItem.style.backgroundColor = "var(--primary-color)";
            pageItem.style.color = "var(--white)";
            pageItem.style.textDecorationColor = "var(--white)";
          });

          checkItem.addEventListener("mouseout", function () {
            pageItem.style.backgroundColor = "";
            pageItem.style.color = "";
            pageItem.style.textDecorationColor = "var(--warning-color)";
          });

          pageItem.addEventListener("click", function () {
            // 移除所有check__item的active类
            document.querySelectorAll(".check__item").forEach(function(item) {
              item.classList.remove("check__item--active");
            });
            // 给当前对应的check__item添加active类
            checkItem.classList.add("check__item--active");
          });
        }
      } catch (error) {
        console.error("Error setting up item relationship:", error);
      }
    });
  }, 100);

  // 添加窗口大小改变时重新计算高度的功能
  window.addEventListener("resize", function () {
    setTimeout(function () {
      pageItems.forEach(function (pageItem) {
        const itemId = pageItem.getAttribute("data-item-id");
        const checkItem = document.querySelector(
          `.check__item[data-item-id="${itemId}"]`
        );

        if (checkItem) {
          const pageItemHeight = pageItem.offsetHeight;
          checkItem.style.height = pageItemHeight + "px";
          checkItem.style.lineHeight = pageItemHeight + "px";
        }
      });
    }, 50);
  });
});
